window.addEventListener('load', function () {
  var form = document.getElementById('form');
  var username = document.getElementById('username');
  var email = document.getElementById('email');
  var password = document.getElementById('password');
  var password2 = document.getElementById('password2');
 
    
  //当输入的信息不符时
  function showError(input, message) {
    var formControl = input.parentElement;
        formControl.className = 'form-control error';
    var small = formControl.querySelector('small');
        small.innerText = message;
  }
  
  // 当输入样式合格时将边框变成绿色色样式
  function showSuccess(input) {
    var formControl = input.parentElement;
    formControl.className = 'form-control success';
  }
  
  //检查邮件有效
  function checkEmail(input) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (re.test(input.value.trim())) {
      showSuccess(input);
    } else {
      showError(input, '邮箱不合法');
    }
  }
  
  //检查所需的字段
  function checkRequired(inputArr) {
    let isRequired = false;
    inputArr.forEach(function(input) {
      if (input.value.trim() === '') {
        showError(input, `${getFieldName(input)}必填`);
        isRequired = true;
      } else {
        showSuccess(input);
      }
    });
  
    return isRequired;
  }
  
  // 检查输入长度
  function checkLength(input, min, max) {
    if (input.value.length < min) {
      showError(input, `${getFieldName(input)}至少 ${min} 个字符`);
    } else if (input.value.length > max) {
      showError(input, `${getFieldName(input)}至多 ${max} 个字符`);
    } else {
      showSuccess(input);
    }
  }
  
  // 检查密码是否正确
  function checkPasswordsMatch(input1, input2) {
    if (input1.value !== input2.value) {
      showError(input2, '密码不匹配');
    }
  }
  
  //获取字段名
  function getFieldName(input) {
    var formControl = input.parentElement;
    var label = formControl.querySelector('label');
    return label.innerText;
  }
  
  // 事件侦听器 判断所有事件是否成功
  form.addEventListener('submit', function (e) {
    e.preventDefault();
    if (!checkRequired([username, email, password, password2])) {
      checkLength(username, 3, 15);
      checkLength(password, 6, 25);
      checkEmail(email);
      checkPasswordsMatch(password, password2);
      window.location.href='succeed.html';

    }
    
  });

  })